//
//  JYPersonalTaxResultViewController.swift
//  JYCalculate
//
//  Created by 何治军 on 2018/10/31.
//  Copyright © 2018 何治军. All rights reserved.
//

import UIKit

class JYPersonalTaxResultViewController: JYBaseViewController,UITableViewDataSource,UITableViewDelegate {
    
    
    var caculateDic:Dictionary<String, String>!
    
    /// 数据
    private var dataArray:[JYHouseLoanModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = Localized("personal-tax-caculate-result");
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        toCaculate()
    }
    
    override func setUpUI() {
        view.addSubview(firstTopView)
        view.addSubview(secondTopView)
        tableview.register(JYHouseLoanCell.self, forCellReuseIdentifier: "JYHouseLoanCell")
        tableview.dataSource = self
        tableview.delegate = self
        view.addSubview(tableview)
    }
    
    override func setDefaultInfo() {

        
    }
    
    override func setTheLayout() {
        firstTopView.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.view)
            make?.top.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
            make?.height.mas_equalTo()(88)
        }
        secondTopView.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.view)
            make?.top.mas_equalTo()(self.firstTopView.mas_bottom)
            make?.right.mas_equalTo()(self.view)
            make?.height.mas_equalTo()(self.firstTopView)
        }
        tableview.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.view)
            make?.top.mas_equalTo()(self.secondTopView.mas_bottom)
            make?.right.mas_equalTo()(self.view)
            make?.bottom.mas_equalTo()(self.view)
        }
    }
    
    /**
     个人所得税计算公式
     应纳税所得额 = （月收入-五险一金-起征点-依法确定的其他扣除-专项附加扣除）
     缴费 = 应纳税所得额*税率 － 速算扣除数
     实发工资=应发工资－四金－缴税
     -----
     年终奖计算公式
     应纳税所得额 = 年终奖金
     应纳税额 = 应纳税所得额 × 适用税率 - 速算扣除数
     */
    func toCaculate() {
        if (self.caculateDic == nil) {
            return
        }
        let caculateType = self.caculateDic["caculateType"]!
        if caculateType == "0" {//计算固定月薪
            for title in ["税前收入","公积金","医疗","养老","失业","工伤","生育"] {
                let model = JYHouseLoanModel()
                model.title = title
                self.dataArray.append(model)
            }
            let money = self.caculateDic["money"]!
            let startLine = self.caculateDic["startLine"]!
            let accumulation = DivisionM(self.caculateDic["accumulation"]!, b: "100").stringValue
            let first = DivisionM(self.caculateDic["first"]!, b: "100").stringValue
            let second = DivisionM(self.caculateDic["second"]!, b: "100").stringValue
            let third = DivisionM(self.caculateDic["third"]!, b: "100").stringValue
            let fourth = DivisionM(self.caculateDic["fourth"]!, b: "100").stringValue
            let fifth = DivisionM(self.caculateDic["fifth"]!, b: "100").stringValue

            let accumulationMoney = MultiplicationM(money, b: accumulation).stringValue
            let firstMoney = MultiplicationM(money, b: first).stringValue
            let secondMoney = MultiplicationM(money, b: second).stringValue
            let thirdMoney = MultiplicationM(money, b: third).stringValue
            let fourthMoney = MultiplicationM(money, b: fourth).stringValue
            let fifthMoney = MultiplicationM(money, b: fifth).stringValue

            self.dataArray[0].descri = "\(money) 元"
            self.dataArray[1].descri = "\(accumulationMoney) 元"
            self.dataArray[2].descri = "\(firstMoney) 元"
            self.dataArray[3].descri = "\(secondMoney) 元"
            self.dataArray[4].descri = "\(thirdMoney) 元"
            self.dataArray[5].descri = "\(fourthMoney) 元"
            self.dataArray[6].descri = "\(fifthMoney) 元"
            
            let wuxianyijin = AdditionM(accumulationMoney, b: AdditionM(fifthMoney,b: AdditionM(fourthMoney,b: AdditionM(thirdMoney,b: AdditionM(secondMoney, b: firstMoney).stringValue).stringValue).stringValue).stringValue).stringValue
            var a = SubtractionM(SubtractionM(money,b: wuxianyijin).stringValue,b: startLine).stringValue//工资应纳税所得额
            
            if !self.calculateIsGreaterFirst(a, second: "0") {
                a = "0"
            }
            var rate = "0"//税率(%)
            var simplified = "0"//速算扣除数
            if self.calculateIsGreaterFirst(a, second: "80000") {
                rate = "45"
                simplified = "15160"
            }else if self.calculateIsGreaterFirst(a, second: "55000") {
                rate = "35"
                simplified = "7160"
            }else if self.calculateIsGreaterFirst(a, second: "35000") {
                rate = "30"
                simplified = "4410"
            }else if self.calculateIsGreaterFirst(a, second: "25000") {
                rate = "25"
                simplified = "2660"
            }else if self.calculateIsGreaterFirst(a, second: "12000") {
                rate = "20"
                simplified = "15160"
            }else if self.calculateIsGreaterFirst(a, second: "3000") {
                rate = "10"
                simplified = "210"
            }else{
                rate = "3"
                simplified = "0"
            }
            
            var b = SubtractionM(MultiplicationM(a,b: DivisionM(rate, b: "100").stringValue).stringValue,b: simplified).stringValue//应纳税额
            if !self.calculateIsGreaterFirst(b, second: "0") {
                b = "0"
            }
            let result = SubtractionM(SubtractionM(money, b: wuxianyijin).stringValue,b: b).stringValue
            self.firstTopView.contentLab.text = result
            self.secondTopView.contentLab.text = b
            self.tableview.reloadData()
        }
        else if caculateType == "1" {//计算年终奖
            for title in ["税前收入"] {
                let model = JYHouseLoanModel()
                model.title = title
                self.dataArray.append(model)
            }
            var money = self.caculateDic["money1"]! //工资应纳税所得额
            if !self.calculateIsGreaterFirst(money, second: "0") {
                money = "0"
            }
            self.dataArray[0].descri = "\(money) 元"
            var rate = "0"//税率(%)
            var simplified = "0"//速算扣除数
            let a = DivisionM(money, b: "12").stringValue //平均每月应纳额
            if self.calculateIsGreaterFirst(a, second: "80000") {
                rate = "45"
                simplified = "15160"
            }else if self.calculateIsGreaterFirst(a, second: "55000") {
                rate = "35"
                simplified = "7160"
            }else if self.calculateIsGreaterFirst(a, second: "35000") {
                rate = "30"
                simplified = "4410"
            }else if self.calculateIsGreaterFirst(a, second: "25000") {
                rate = "25"
                simplified = "2660"
            }else if self.calculateIsGreaterFirst(a, second: "12000") {
                rate = "20"
                simplified = "15160"
            }else if self.calculateIsGreaterFirst(a, second: "3000") {
                rate = "10"
                simplified = "210"
            }else{
                rate = "3"
                simplified = "0"
            }
            var b = SubtractionM(MultiplicationM(money,b:DivisionM(rate,b: "100").stringValue).stringValue,b: simplified).stringValue//应纳税额
            if !self.calculateIsGreaterFirst(b, second: "0") {
                b = "0"
            }
            let result = SubtractionM(money,b:b).stringValue
            self.firstTopView.contentLab.text = result
            self.secondTopView.contentLab.text = b
            self.tableview.reloadData()
        }
    }
    
    //比较first是否大于second
    func calculateIsGreaterFirst(_ first:String , second:String) ->Bool {
        let  num1 = NSDecimalNumber.init(string: first)
        let  num2 = NSDecimalNumber.init(string: second)
        let result = num1.compare(num2)
        if result == .orderedDescending {
            return true
        }else{
            return false
        }
    }
    
    //MARK: - UITableViewDataSource,UITableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = JYHouseLoanCell.init(style: .default, reuseIdentifier: "JYHouseLoanCell")
        cell.model = self.dataArray[indexPath.row]
        cell.selectionStyle = .none
        if indexPath.row == 0 {
            cell.topLine.isHidden = false
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    // MARK: - 懒加载b
    private lazy var tableview:UITableView = {
        let tab = UITableView()
        tab.separatorStyle = .none
        tab.backgroundColor = JYVCBackGroundColor
        return tab
    }()
    
    private lazy var firstTopView:JYHouseLoanResultTopView = {
        let v = JYHouseLoanResultTopView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        v.titleLab.text = "到手所得:(元)"
        return v
    }()
    private lazy var secondTopView:JYHouseLoanResultTopView = {
        let v = JYHouseLoanResultTopView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        v.titleLab.text = "个人所得税:(元)"
        return v
    }()
}

